package org.easyx.api.sys.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.List;

import javax.validation.Valid;

import org.easyx.api.base.ApiBaseController;
import org.easyx.core.utils.ObjKit;
import org.easyx.ser.sys.entity.SysUser;
import org.easyx.ser.sys.serivce.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;


@Controller
@RequestMapping("/api/sysUser")
@Api(value="系统用户接口",produces=MediaType.APPLICATION_JSON_VALUE)
public class SysUserController extends ApiBaseController{
	private static final Logger log = LoggerFactory.getLogger(SysUserController.class);
	
	@Autowired
	private SysUserService sysUserService;
	
	@ApiOperation(value="新增",notes="新增",httpMethod="POST",produces=MediaType.APPLICATION_JSON_VALUE)
	@RequestMapping("/add")
	public @ResponseBody Object add(@Valid SysUser entity, BindingResult result){
		try {
			if(result.hasErrors()){
				return operateError(result.getAllErrors().get(0).getDefaultMessage());
			}
			
			/** 数据唯一性校验 */
			List<SysUser> listByLoginName = sysUserService.selectList(
						new EntityWrapper<SysUser>().eq("loginName",entity.getLoginName()));
			if(ObjKit.isNotEmpty(listByLoginName)){
				return operateError("账号【"+entity.getLoginName()+"】已经存在，请重新填写");
			}
			List<SysUser> listByRealName = sysUserService.selectList(
					new EntityWrapper<SysUser>().eq("realName",entity.getRealName()));
			if(ObjKit.isNotEmpty(listByRealName)){
				return operateError("账号【"+entity.getRealName()+"】已经存在，请重新填写");
			}

			//插入数据库
			sysUserService.insert(entity);
			
			return operateSuccess("数据添加成功");
		} catch (Exception e) {
			log.error("添加数据出现异常:", e);
			return operateError("保存数据失败");
		}
	}
	
	
}
